using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityStandardAssets.CrossPlatformInput;

namespace VoxelEngine
{
	public class VirtualJoystickController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IEventSystemHandler
	{
		[SerializeField]
		private Image _image;

		[SerializeField]
		private float _maxRadius = 1f;

		[SerializeField]
		private Camera _uiCamera;

		private Vector2 _screenPosition;

		private float _radius;

		public Action<Vector2> Moved;

		public Action Dropped;

		private readonly CrossPlatformInputManager.VirtualAxis _horizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis("Horizontal");

		private readonly CrossPlatformInputManager.VirtualAxis _verticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis("Vertical");

		private void Awake()
		{
			Vector2 sizeDelta = _image.rectTransform.sizeDelta;
			_radius = sizeDelta.x / 2f;
			CrossPlatformInputManager.RegisterVirtualAxis(_horizontalVirtualAxis);
			CrossPlatformInputManager.RegisterVirtualAxis(_verticalVirtualAxis);
		}

		private void OnDestroy()
		{
			CrossPlatformInputManager.UnRegisterVirtualAxis("Horizontal");
			CrossPlatformInputManager.UnRegisterVirtualAxis("Vertical");
		}

		private void Update()
		{
		}

		public void OnDrag(PointerEventData eventData)
		{
			Vector3 zero = Vector3.zero;
			Vector2 position = eventData.position;
			zero.x = (int)(position.x - _screenPosition.x);
			Vector2 position2 = eventData.position;
			zero.y = (int)(position2.y - _screenPosition.y);
			Move(zero);
		}

		private void Move(Vector3 delta)
		{
			float num = _radius * _maxRadius;
			if (delta.sqrMagnitude > num * num)
			{
				delta = delta.normalized * num;
			}
			_image.transform.localPosition = delta;
			_horizontalVirtualAxis.Update(delta.x / (_maxRadius * _radius));
			_verticalVirtualAxis.Update(delta.y / (_maxRadius * _radius));
			Moved.Fire(new Vector2(delta.x, delta.y));
		}

		public void OnPointerDown(PointerEventData eventData)
		{
			_screenPosition = _uiCamera.WorldToScreenPoint(_image.transform.position);
		}

		public void OnPointerUp(PointerEventData eventData)
		{
			_image.transform.localPosition = Vector3.zero;
			_horizontalVirtualAxis.Update(0f);
			_verticalVirtualAxis.Update(0f);
			Dropped.Fire();
		}
	}
}
